//
//  DetailsViewController.swift
//  许鲜
//
//  Created by hbl on 16/4/26.
//  Copyright © 2016年 hbl. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class DetailsViewController: UIViewController {
    var numberLabel:UILabel?
    var beginPoint:CGPoint?
    var goodsModel:GoodsModel?{
        didSet{
            photo.yy_setImageWithURL(NSURL(string: (goodsModel?.newimg)!), placeholder: nil)
            titleMessage.text = goodsModel?.title
            realPrice.text = goodsModel?.laouser
            discountImageView.yy_setImageWithURL(NSURL(string: (goodsModel?.tipsimg)!), placeholder: nil)
            
            price.text = goodsModel?.market_price
            standard.text = goodsModel?.unit
        }
    }
    
   lazy var mainScroller:UIScrollView = {
        let mainScroller = UIScrollView()
        mainScroller.frame = UIScreen.mainScreen().bounds
        mainScroller.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(mainScroller)
        return mainScroller
    }()
    
    lazy var photo:UIImageView = {
        let photo = UIImageView()
        photo.frame = CGRectMake(0, mainH/3 * 0.5, mainW, mainH * 1/3)
        photo.layer.anchorPoint = CGPointMake(0.5, 1)
        return photo
    }()
    
    lazy var titleMessage:UILabel = {
        let titleMessage = UILabel()
        titleMessage.frame = CGRectMake(30, CGRectGetMaxY(self.photo.frame) + 10, mainW - 60, 20)
        titleMessage.font = UIFont.systemFontOfSize(17, weight: 0.7)
        return titleMessage
    }()
    
    lazy var realPrice:UILabel = {
        let realPrice = UILabel()
        realPrice.frame = CGRectMake(30, CGRectGetMaxY(self.titleMessage.frame) + 15, 80, 25)
        realPrice.font = UIFont.systemFontOfSize(17, weight: 1)
        realPrice.textColor = UIColor.orangeColor()
        return realPrice
    }()
    
    lazy var discountImageView:UIImageView = {
        let discountImageView = UIImageView()
        discountImageView.frame = CGRectMake(CGRectGetMaxX(self.realPrice.frame) + 15, self.realPrice.frame.origin.y + 5, 65, 15)
        return discountImageView
    }()
    
    lazy var line:UIView = {
        let line = UIView()
        line.frame = CGRectMake(30, CGRectGetMaxY(self.realPrice.frame) + 5, mainW - 60, 1)
        line.backgroundColor = UIColor(white: 0, alpha: 0.2)
        return line
    }()
    
    lazy var price:UILabel = {
        let price = UILabel()
        price.frame = CGRectMake(30, CGRectGetMaxY(self.line.frame) + 5, 150, 15)
        price.font = UIFont.systemFontOfSize(13)
        price.textColor = UIColor.lightGrayColor()
        return price
    }()
    
    lazy var standard:UILabel = {
        let standard = UILabel()
        standard.frame = CGRectMake(CGRectGetMaxX(self.price.frame) + 20, self.price.frame.origin.y, 200, 15)
        standard.font = UIFont.systemFontOfSize(13)
        standard.textColor = UIColor.orangeColor()
        return standard
    }()
    
    lazy var detailView:UIView = {
        let detailView = UIView()
        detailView.frame = CGRectMake(0, CGRectGetMaxY(self.standard.frame) + 20, mainW, 30)
        detailView.backgroundColor = UIColor(white: 0.97, alpha: 1)
        return detailView
    }()
    
    lazy var detailLine1:UIView = {
        var detailLine1 = UIView()
        detailLine1.frame = CGRectMake(0, 0, mainW, 1)
        detailLine1.backgroundColor = UIColor(white: 0, alpha: 0.1)
        return detailLine1
    }()
    
    lazy var detailLine2:UIView = {
        var detailLine2 = UIView()
        detailLine2.frame = CGRectMake(0, 29, mainW, 1)
        detailLine2.backgroundColor = UIColor(white: 0, alpha: 0.1)
        return detailLine2
    }()
    
    lazy var detailLabel:UILabel = {
        let detailLabel = UILabel()
        detailLabel.frame = CGRectMake(0, 0, mainW, 30)
        detailLabel.text = "  商品详情"
        detailLabel.font = UIFont.systemFontOfSize(15)
        detailLabel.textColor = UIColor(white: 0.5, alpha: 1)
        return detailLabel
    }()
    
    lazy var detailWeb:UIWebView = {
        
        var detailWeb = UIWebView()
        detailWeb.frame = CGRectMake(0, CGRectGetMaxY(self.detailView.frame), mainW, 10)
        detailWeb.delegate = self
        let urlStr = "http://mobile.xuxian.com/goods/getGoodsDetail/\(self.goodsModel!.id!)?ver=2015121401"
        //let a = self.goodsModel!.goods_id
        let request = NSURLRequest(URL: NSURL(string:urlStr)!)
        detailWeb.scrollView.scrollEnabled = false
        detailWeb.loadRequest(request)
        SVProgressHUD.showWithStatus("正在加载...")
        return detailWeb
    }()
    
    lazy var bottomBar:UIView = {
        let bottomBar = UIView()
        bottomBar.frame = CGRectMake(0, mainH - 44, mainW, 44)
        bottomBar.backgroundColor = UIColor(white: 0.99, alpha: 1)
        self.view.addSubview(bottomBar)
        return bottomBar
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupScrollerView()
        setupTitleBtn()
        setupBottomBar()
        view?.layer.anchorPoint = CGPointMake(0.5, 4)
        view.mj_y = mainH * 3.5
    }
    
    private func setupScrollerView(){
        mainScroller.addSubview(photo)
        mainScroller.addSubview(titleMessage)
        mainScroller.addSubview(discountImageView)
        mainScroller.addSubview(realPrice)
        mainScroller.addSubview(line)
        mainScroller.addSubview(price)
        mainScroller.addSubview(standard)
        mainScroller.addSubview(detailView)
        detailView.addSubview(detailLine1)
        detailView.addSubview(detailLine2)
        detailView.addSubview(detailLabel)
        mainScroller.addSubview(detailWeb)
        mainScroller.contentInset = UIEdgeInsetsMake(0, 0, 44, 0)
        mainScroller.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 44, 0)
        mainScroller.delegate = self
        let pan = UIPanGestureRecognizer(target: self, action:#selector(pan(_:)))
        pan.delegate = self
        view.addGestureRecognizer(pan)
        
    }
    
    func pan(pan:UIPanGestureRecognizer){
        let delat = pan.locationInView(UIApplication.sharedApplication().keyWindow).x - (beginPoint?.x)!
        let r = mainH * 4 - (beginPoint?.y)!
        let view = pan.view
        view?.transform = CGAffineTransformMakeRotation(delat/r)
        if pan.state == UIGestureRecognizerState.Ended{
            if delat/r < CGFloat(M_PI*5 / 180) && delat/r > -CGFloat(M_PI*5 / 180){
                UIView.animateWithDuration(0.8, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.5, options: UIViewAnimationOptions(rawValue: 0), animations: {
                    view?.transform = CGAffineTransformIdentity
                    }, completion: nil)
            }else{
                UIView.animateWithDuration(0.25, animations: {
                    if delat > 0{
                        view?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
                    }else{
                        view?.transform = CGAffineTransformMakeRotation(-CGFloat(M_PI_4))
                    }
                    
                    }, completion: { (_) in
                        self.dismissViewControllerAnimated(false, completion: nil)
                })
            }
        }
       
    }
    
    private func setupBottomBar(){
        let minusBtn = UIButton()
        minusBtn.frame = CGRectMake(15, 0, 44, 44)
        minusBtn.setImage(UIImage(named: "减少按钮"), forState: UIControlState.Normal)
        minusBtn.contentEdgeInsets = UIEdgeInsetsMake(7, 7, 7, 7)
        minusBtn.addTarget(self, action: #selector(DetailsViewController.minusClick), forControlEvents: UIControlEvents.TouchUpInside)
        bottomBar.addSubview(minusBtn)
        
        let number = UILabel()
        number.frame = CGRectMake(CGRectGetMaxX(minusBtn.frame), 0, 44, 44)
        number.text = "1"
        number.textColor = UIColor(white: 0.5, alpha: 1)
        number.textAlignment = NSTextAlignment.Center
        bottomBar.addSubview(number)
        numberLabel = number
        
        let plusBtn = UIButton()
        plusBtn.frame = CGRectMake(CGRectGetMaxX(number.frame), 0, 44, 44)
        plusBtn.setImage(UIImage(named: "增加按钮"), forState: UIControlState.Normal)
        plusBtn.contentEdgeInsets = UIEdgeInsetsMake(7, 7, 7, 7)
        plusBtn.addTarget(self, action: #selector(DetailsViewController.plusClick), forControlEvents: UIControlEvents.TouchUpInside)
        bottomBar.addSubview(plusBtn)
        
        let addBtn = UIButton()
        addBtn.bounds = CGRectMake(0, 0, 120, 34)
        addBtn.center = CGPointMake(mainW - 85, bottomBar.mj_h/2)
        addBtn.setBackgroundImage(UIImage(named: "navBg")!, forState: UIControlState.Normal)
        addBtn.setTitle("购物车", forState: UIControlState.Normal)
        addBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        addBtn.clipsToBounds = true
        addBtn.layer.cornerRadius = 5
        addBtn.addTarget(self, action: #selector(DetailsViewController.addClick), forControlEvents: UIControlEvents.TouchUpInside)
        bottomBar.addSubview(addBtn)

    }
    
    func addClick(){
        let goods = ShoppingGoods.shareShopping()
        goods.goodsArray.append(goodsModel!)
        goods.numArray.append("×" + (numberLabel?.text)!)
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        SVProgressHUD.showSuccessWithStatus("已加入购物车！")
        
    }
    func minusClick(){
        var count:Int = Int((numberLabel?.text)!)!
        if count > 1 {
            count = count - 1
        }
        numberLabel?.text = "\(count)"
    }
    
    func plusClick(){
        var count:Int = Int((numberLabel?.text)!)!
        count = count + 1
        numberLabel?.text = "\(count)"
    }
    func setupTitleBtn(){
        let back = UIButton()
        back.frame = CGRectMake(15, 30, 25, 25)
        back.setImage(UIImage(named: "返回"), forState: UIControlState.Normal)
        back.addTarget(self, action: #selector(DetailsViewController.back), forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(back)
        
        let share = UIButton()
        share.frame = CGRectMake(mainW - 40, 30, 25, 25)
        share.setImage(UIImage(named: "分享"), forState: UIControlState.Normal)
        view.addSubview(share)
    }
    
    func back(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}

extension DetailsViewController:UIWebViewDelegate,UIScrollViewDelegate,UIGestureRecognizerDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
       let height = webView.scrollView.contentSize.height
        detailWeb.frame.size.height = height
        mainScroller.contentSize = CGSize(width: 0, height: CGRectGetMaxY(detailWeb.frame))
        SVProgressHUD.dismiss()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if scrollView.contentOffset.y < 0 {
            let delat = -(scrollView.contentOffset.y)
            let scale = (mainH/3 + delat)/(mainH/3)
            
            photo.transform = CGAffineTransformMakeScale(scale,scale)
            
            
        }
    }
    
    func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
       beginPoint = gestureRecognizer.locationInView(UIApplication.sharedApplication().keyWindow)
       // print(beginPoint)
        
        return true
    }
    
    
}
